package com.haoze.common.utils;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 树形数据构建工具。
 *
 * @author zj
 * @time 2019-03-01。
 */
public class TreesBuildUtil {

    public static <T> Trees<T> build(List<Trees<T>> nodes) {

        if (nodes == null) {
            return null;
        }
        List<Trees<T>> topNodes = new ArrayList<>();

        for (Trees<T> children : nodes) {

            String pid = children.getParentId();
            String type = children.getType();
            String element = children.getElementId();
            if (pid == null || "0".equals(pid)) {
                topNodes.add(children);
                continue;
            }

            for (Trees<T> parent : nodes) {
                String id = parent.getId();
                if (id != null && id.equals(element)) {
                    Map<String, List<Trees<T>>> child = new HashMap<>();
                    for (Trees<T> example : nodes) {
                        List<Trees<T>> newform = new ArrayList<>();
                        if (example.getParentId().equals(id)) {
                            for(Trees<T> first : nodes) {
                                if(first.getElementId() != null){
                                    if (first.getElementId().equals(example.getParentId()) && first.getParentId().equals(example.getId())) {
                                        newform.add(first);
                                        child.put(first.getParentId(), newform);
                                    }
                                }
                            }
                            parent.setChildren(child);
                            children.setHasParent(true);
                            continue;
                        }
                    }
                }
                else if(id != null && id.equals(pid) && ("21".equals(type)||"22".equals(type))){
                    parent.getOptions().add(children);
                    children.setHasParent(true);
                    parent.setChildren(true);
                    continue;
                }
            }
        }

        Trees<T> root = new Trees();
        if (topNodes.size() == 1) {
            root = topNodes.get(0);
        } else {
//            root.setId("1");
//            root.setParentId("0");
//            root.setHasParent(false);
//            root.setChildren(true);
//            root.setChecked(true);
//            root.setChildren(topNodes);
//            root.setText("首次病程录数据集");
            Map<String, Object> state = new HashMap<>(16);
            state.put("opened", true);
            root.setState(state);
        }
        return root;
    }

}